<?php

/**
 * @name AdminController
 * @author fudaoji
 * @desc 管理员操作控制器
 */

class AdminController extends Ctrl_Base{

	public $commonModel ;
	public $studentModel;
	public $numberOfPage = 20; //每页显示条数

	/**
	 * @desc初始化操作
	 */
	public function init(){
		parent::init();
		$this->auth();
		$this->commonModel = new CommonModel();
		$this->studentModel = new StudentModel();
	}

	/*********************************学生操作开始************************/

	/**
	 *@desc显示所有学生信息
	 *@param string $page 跳转页码
	 */
	public function showStudentsAction($page=1){
		//获取所有学生信息
		$allStudent   = $this->studentModel->getAllStudent();

		//获取student表的所有字段名
		$fieldName    = $this->studentModel->field;

		$classModel   = new ClassModel('class_id');
		$majorModel   = new MajorModel('major_id');

		//获取所有班级信息
		$allClass     = $classModel->getAllClassInfo();
		//获取所有专业信息
		$allMajor     = $majorModel->getAllMajorInfo();

		$sex          = $this->parameters['sex'];

		//分页框
		$currentPage  = $page?$page:1;
		$numberOfPage = $this->numberOfPage;
		$totalPages   = ceil(count($allStudent)/$numberOfPage);
		if ($allStudent && $currentPage>$totalPages) {
			header("Location: ".SITE_ROOT."admin/error/msg/您访问了不存在页面");
				exit();
		}
		$url 		  = SITE_ROOT."admin/show-students/page/";
		$pagination   = $this->commonModel->paginator($currentPage, $totalPages, $url);
		//得到当页要显示的学生信息
		$allStudent   = array_slice($allStudent, ($currentPage-1)*$numberOfPage, $numberOfPage); 
		
		$this->assign(array('allStudent' => $allStudent,
							'fieldName'  => $fieldName,
							'allClass'   => $allClass,
							'allMajor'	 => $allMajor,
							'sex'        => $sex,
							'pagination' => $pagination));
	}

	/**
	 * @desc 添加学生
	 */
	public function addStudentAction(){
		$classModel   = new ClassModel('class_id');
		$majorModel   = new MajorModel('major_id');
		//获取全部班级的信息
		$allClass     = $classModel->getAllClassInfo();
		//获取全部专业的信息
		$allMajor     = $majorModel->getAllMajorInfo();

		$sex          = $this->parameters['sex'];

 		$this->assign(array('allClass' => $allClass,
 							'allMajor' => $allMajor,
 							'sex'      => $sex));

 		//从表单获取数据并保存数据
		if ($uid = trim($this->post('uid'))) {
			$pwd      = trim($this->post('pwd'));
			$name     = trim($this->post('name'));
			$sex      = intval($this->post('sex'));
			$major_id = trim($this->post('major_id'));
			$class_id = trim($this->post('class_id'));
			$phone    = trim($this->post('phone'));

			$form     = array('uid'=>$uid,'pwd'=>$pwd,'name'=>$name,
							  'major_id'=>$major_id,'class_id'=>$class_id);
			$stuInfo  = array_merge($form, array('sex'=>$sex,'phone'=>$phone));
	
			//验证必填项信息
			if (!$this->commonModel->isNull($form)) {
				$this->ajax(false, $this->parameters['errMsg'][1]);
			}

			//将用户信息插入auth_user表中
			$userModel = new LoginModel();
			/*if (!$student) {
				$this->ajax(false, $student['sex'],1);
			}*/
			$num = $userModel->insertUser(array('uid'=>$uid,'mid'=>3,'password'=>$pwd));
			if($num==0){
				//保存数据到student表中
				$result = $this->studentModel->insertStudent($stuInfo);
				($result==9) && $this->ajax(false,$this->parameters['errMsg'][9],1);
				if($result==0){
					$classModel->addPersonNum($class_id);
					$this->ajax(true,$this->parameters['okMsg'][2]);
				}
			}else{
				($num==8) && $this->ajax(false,$this->parameters['errMsg'][8],8);
				$this->ajax(false,$this->parameters['errMsg'][9], 1);
			}
		}
	}

	/**
	 * @desc 修改学生数据
	 */
	public function updateStudentAction(){

		$id = $this->get('id');
		if ($id=trim($id)) {
			$student = $this->studentModel->getOneStudent($id);
			$classModel   = new ClassModel('class_id');
			$majorModel   = new MajorModel('major_id');
			//获取全部班级的信息
			$allClass     = $classModel->getAllClassInfo();
			//获取全部专业的信息
			$allMajor     = $majorModel->getAllMajorInfo();

			$sex          = $this->parameters['sex'];

			$this->assign(array('allClass' => $allClass,
	 							'allMajor' => $allMajor,
	 							'student'  => $student,
	 							'sex'      => $sex));
		}

 		//从表单获取数据并保存数据
		if ($uid = trim($this->post('uid'))) {
			$oldUid   = trim($this->post('oldUid'));
			$name     = trim($this->post('name'));
			$sex      = intval($this->post('sex'));
			$position = trim($this->post('position'));
			$major_id = trim($this->post('major_id'));
			$class_id = trim($this->post('class_id'));
			$email    = trim($this->post('email'));
			$phone    = trim($this->post('phone'));

			$form     = array('uid'=>$uid,'name'=>$name,
							  'major_id'=>$major_id,
							  'class_id'=>$class_id);
			$stuInfo  = array_merge($form, array('sex'=>$sex,'position'=>$position,
												 'email'=>$email,'phone'=>$phone));

			//验证必填项信息
			if (!$this->commonModel->isNull($form)) {
				$this->ajax(false, $this->parameters['errMsg'][1]);
			}

			//修改前的信息
			$student = $this->studentModel->getOneStudent($uid);
			//保存数据到student表中
			$result = $this->studentModel->updateStudent($stuInfo);
			($result==12) && $this->ajax(false,$this->parameters['errMsg'][12],1);
			if($result==0){
				//如果更改了所在班级，则应更新新、旧班级的人数
				if($student['class_id']!=$class_id){
					$classModel = new ClassModel('class_id');
					$classModel->reducePersonNum($student['class_id']);
					$classModel->addPersonNum($class_id);
				}
				$this->ajax(true);
			}
		}
	}

	/**
	 * @desc 删除指定的学生
	 */
	public function deleteStudentAction(){

		$uid = $this->get('id');
		(!$uid) && 
			header("Location: ".SITE_ROOT."admin/error/msg/".$this->parameters['errMsg'][10]);

		$classModel = new ClassModel();
		$loginModel  = new LoginModel(); 
		$student    = $this->studentModel->getOneStudent($uid);

		//从student表中删除数据
		$result = $this->studentModel->deleteStudent($uid);
		if ($result==0) {
			//从auth_user表中删除数据
			$loginModel->deleteUser($student['uid']);
			//更新class的persons字段
			$classModel->reducePersonNum($student['class_id']);
			$msg = $this->parameters['okMsg'][3];
			header("Location: ".SITE_ROOT."admin/success/msg/".$msg);
			exit();
		}
		header("Location: ".SITE_ROOT."admin/error/msg/".$this->parameters['errMsg'][10]);
		exit();
	}

	/**
	 * @desc 导出学生信息以excel格式保存
	 */
	public function downLoadStudentAction($cid=''){

		$sheetTitle = "学生信息表";
		/*获取所有学生信息*/
		if ($cid=trim($cid)){
			$classModel = new ClassModel();
			$class = $classModel->getOneClass($cid);
			$allStudent   = $this->studentModel->getStudentsByCid($cid);
			$sheetTitle   = $class['classname']."班学生信息表";
		}
		else
			$allStudent   = $this->studentModel->getAllStudent();
		$dataList = array();
		foreach ($allStudent as $key => $value) {
			$dataList[$key]['A'] = $value['uid'];
			$dataList[$key]['B'] = $value['name'];
			$dataList[$key]['C'] = $value['sex'];
		}
		$fieldName    = $this->studentModel->field;

		//获取专业和班级信息
		$classModel   = new ClassModel('class_id');
		$majorModel   = new MajorModel('major_id');
		$allClass     = $classModel->getAllClassInfo();
		$allMajor     = $majorModel->getAllMajorInfo();
		//获取性别
		$sex          = $this->parameters['sex'];

		$this->inputExcelClass();
		$field = array('A'=>'学号','B'=>'姓名','C'=>'性别');
		$filePath = $this->excelFile;
		PHPExcelExport::getExportPage($filePath,0,$sheetTitle,1,$field,2,$dataList);
	}

	/**
	 * @desc 接收excel文件导入学生信息
	 */
	public function upLoadStudentAction(){
		if ($_POST) {

			$upload_dir     = WWW_ROOT . "uploads/student";
			$errUrl         = "admin/error/";
			$fileFieldName  = 'infoFile';
			$excelModel     = new ExcelModel();

			//确定存放文件的文件夹存在
			$excelModel->createUploadsDir($upload_dir, $errUrl);

			//文件上传可能出现的错误
			$excelModel->getErrors($fileFieldName);
			 
			//文件重命名
			$fileName = $excelModel->renameFile($upload_dir."/",$fileFieldName);

			//储存文件
			if (move_uploaded_file($_FILES[$fileFieldName]['tmp_name'],$fileName)){
			
				date_default_timezone_set('Asia/Shanghai');
				$inputFileName = $fileName;
				$objPHPExcel = PHPExcel_IOFactory::load($inputFileName) or
					header("Location: ".SITE_ROOT.$errUrl."msg/文件不存在");
				//从文件中读取数据
				$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
				$sheetData = array_slice($sheetData, 1);

				//将数据保存到数据库中
				foreach ($sheetData as $data) {
					$stuInfo = array('uid'=>$data['A'],'name'=>$data['B'],
							'major_id'=>$data['C'],'class_id'=>$data['D']);
					$userInfo = array('uid'=>$data['A'], 'mid'=>3, 'password'=>$data['A']);

					$userModel = new LoginModel();
					$num = $userModel->insertUser($userInfo);
					if($num==0){
						//保存数据到student表中
						$result = $this->studentModel->insertStudent($stuInfo);
						if($result==0){
							$classModel = new ClassModel('class_id');
							$classModel->addPersonNum($stuInfo['class_id']);
						}
					}

				}
				header("Location: ".SITE_ROOT."admin/success/msg/".$this->parameters['okMsg'][5]);
			}else{
				header("Location: ".SITE_ROOT.$errUrl."msg/".$this->parameters['errMsg'][11]);
				exit();
			}


		}

	}

	/**
	 * @desc 搜索指定的学生
	 */
	public function searchStudentAction(){
		$searchKey = trim($this->get('searchKey'));
		//(!$searchKey) && $this->ajax(false,$this->parameters['errMsg'][13],13);
		$allStudent = array();
		$display   = false;
		if ($student = $this->studentModel->getOneStudent($searchKey)) {
			$display = true;
			$allStudent[] = $student;
		}else{
			$allStudent = $this->studentModel->getStudentsByName($searchKey);
			if (!empty($allStudent)) {
				$display = true;
			}
		}
		if ($display==true) {
			//获取student表的所有字段名
			$fieldName    = $this->studentModel->field;

			$classModel   = new ClassModel('class_id');
			$majorModel   = new MajorModel('major_id');

			//获取所有班级信息
			$allClass     = $classModel->getAllClassInfo();
			//获取所有专业信息
			$allMajor     = $majorModel->getAllMajorInfo();

			$sex          = $this->parameters['sex'];

			$this->assign(array('allStudent' => $allStudent,
								'fieldName'  => $fieldName,
								'allClass'   => $allClass,
								'allMajor'	 => $allMajor,
								'sex'        => $sex,));
		}
	}

	/*********************************学生操作结束************************/

	/*********************************教师操作开始************************/

	/**
	 *@desc显示所有教师信息
	 *@param string $page 跳转页码
	 */
	public function showTeachersAction($page=1){
		$teacherModel = new TeacherModel();

		//获取所有教师信息
		$allTeacher   = $teacherModel->getAllTeacher();

		//获取teacher表的所有字段名
		$fieldName    = $teacherModel->field;
		$sex          = $this->parameters['sex'];

		//分页框
		$currentPage  = $page?$page:1;
		$numberOfPage = $this->numberOfPage;
		$totalPages   = ceil(count($allTeacher)/$numberOfPage);
		if ($allteacher && $currentPage>$totalPages) {
			header("Location: ".SITE_ROOT."admin/error/msg/您访问了不存在页面");
				exit();
		}
		$url 		  = SITE_ROOT."admin/show-teachers/page/";
		$pagination   = $this->commonModel->paginator($currentPage, $totalPages, $url);
		//得到当页要显示的学生信息
		$allTeacher   = array_slice($allTeacher, ($currentPage-1)*$numberOfPage, $numberOfPage); 
		
		$this->assign(array('allTeacher' => $allTeacher,
							'fieldName'  => $fieldName,
							'sex'        => $sex,
							'pagination' => $pagination));
	}

	/**
	 * @desc 添加教师
	 */
	public function addTeacherAction(){

		$sex = $this->parameters['sex'];
 		$this->assign(array('sex' => $sex));

 		//从表单获取数据并保存数据
		if ($uid = trim($this->post('uid'))) {
			$pwd      = trim($this->post('pwd'));
			$name     = trim($this->post('name'));
			$sex      = intval($this->post('sex'));
			$position = trim($this->post('position'));
			$email    = trim($this->post('email'));
			$phone    = trim($this->post('phone'));

			$form     = array('uid'=>$uid,'pwd'=>$pwd,'name'=>$name);
			$teacherInfo = array_merge($form, array('sex'=>$sex,'phone'=>$phone,
													'position'=>$position,
													'email'=>$email));
	
			//验证必填项信息
			if (!$this->commonModel->isNull($form)) {
				$this->ajax(false, $this->parameters['errMsg'][1]);
			}

			//将用户信息插入auth_user表中
			$userModel = new LoginModel();
			$num = $userModel->insertUser(array('uid'=>$uid,'mid'=>2,'password'=>$pwd));
			if($num==0){
				//保存数据到teacher表中
				$teacherModel = new TeacherModel();
				$result = $teacherModel->insertTeacher($teacherInfo);
				($result==9) && $this->ajax(false,$this->parameters['errMsg'][9],1);
				if($result==0){
					$this->ajax(true,$this->parameters['okMsg'][7],7);
				}
			}else{
				($num==8) && $this->ajax(false,$this->parameters['errMsg'][8],8);
				$this->ajax(false,$this->parameters['errMsg'][9], 1);
			}
		}
	}

	/**
	 * @desc 修改教师信息
	 */
	public function updateTeacherAction(){

		$id = $this->get('id');
		$teacherModel = new TeacherModel();
		if ($id=trim($id)) {
			$teacher = $teacherModel->getOneTeacher($id);
			$sex     = $this->parameters['sex'];
			$this->assign(array('sex'     => $sex,
								'teacher' => $teacher));
		}

 		//从表单获取数据并保存数据
		if ($uid = trim($this->post('uid'))) {
			$name     = trim($this->post('name'));
			$sex      = intval($this->post('sex'));
			$phone    = trim($this->post('phone'));
			$position = trim($this->post('position'));
			$email    = trim($this->post('email'));

			$form     = array('uid'=>$uid,'name'=>$name);
			$teacherInfo = array_merge($form, array('sex'=>$sex,'phone'=>$phone,
													'position'=>$position,
													'email'=>$email));

			//验证必填项信息
			if (!$this->commonModel->isNull($form)) {
				$this->ajax(false, $this->parameters['errMsg'][1]);
			}

			$result = $teacherModel->updateTeacher($teacherInfo);
			($result==12) && $this->ajax(false,$this->parameters['errMsg'][12],1);
			if($result==0){
				$this->ajax(true,$this->parameters['okMsg'][6]);
			}
		}
	}

	/**
	 * @desc 删除指定的学生
	 */
	public function deleteTeacherAction(){

		$uid = $this->get('id');
		(!$uid) && 
			header("Location: ".SITE_ROOT."admin/error/msg/".$this->parameters['errMsg'][10]);

		$teacherModel = new TeacherModel(); 
		$teacher      = $teacherModel->getOneTeacher($uid);

		//从teacher表中删除数据
		$result = $teacherModel->deleteTeacher($uid);
		if ($result==0) {
			//从auth_user表中删除数据
			$loginModel = new LoginModel();
			$loginModel->deleteUser($teacher['uid']);
			$msg = $this->parameters['okMsg'][3];
			header("Location: ".SITE_ROOT."admin/success/msg/".$msg);
			exit();
		}
		header("Location: ".SITE_ROOT."admin/error/msg/".$this->parameters['errMsg'][10]);
		exit();
	}

	/**
	 * @desc 导出教师信息以excel格式保存
	 */
	public function downLoadTeacherAction(){

		/*获取所有教师信息*/
		$teacherModel = new TeacherModel();
		$allTeacher   = $teacherModel->getAllTeacher();
		$fieldName    = $teacherModel->field;

		//获取性别
		$sex          = $this->parameters['sex'];

		date_default_timezone_set('Asia/Shanghai');

		if (PHP_SAPI == 'cli')
			die('请使用浏览器进行操作！');

		// 生成 PHPExcel 对象
		$objPHPExcel = new PHPExcel();

		//设置文件属性
		$objPHPExcel->getProperties()->setCreator("傅道集")
									 ->setTitle("教师信息表")//文档名称
									 ->setSubject("教师信息表")
									 ->setDescription("理学院教师基本信息")
									 ->setKeywords("教师 信息");
		//添加列名称
		$objPHPExcel->setActiveSheetIndex(0)
		            ->setCellValue('A1', $fieldName['uid']['comment'])
		            ->setCellValue('B1', $fieldName['name']['comment'])
		            ->setCellValue('C1', $fieldName['sex']['comment'])
		            ->setCellValue('D1', $fieldName['position']['comment'])
		            ->setCellValue('E1', $fieldName['email']['comment'])
		            ->setCellValue('F1', $fieldName['phone']['comment']);

		//添加具体信息
		$i = 2;
		foreach ($allTeacher as $teacher) {
			$objPHPExcel->setActiveSheetIndex(0) 
		            ->setCellValue('A'.$i, $teacher['uid'])
		            ->setCellValue('B'.$i, $teacher['name'])
		            ->setCellValue('C'.$i, $sex[$teacher['sex']])
		            ->setCellValue('D'.$i, $teacher['position'])
		            ->setCellValue('E'.$i, $student['email'])
		            ->setCellValue('F'.$i, $student['phone']);
		    $i++;
		}

		//更改sheet名
		$objPHPExcel->getActiveSheet()->setTitle('教师信息表');  

		//设置打开文件时显示的sheet
		$objPHPExcel->setActiveSheetIndex(0);  


		//设置文件类型
		header('Content-Type: application/vnd.ms-excel');  
		//设置默认的文件名
		header('Content-Disposition: attachment;filename="教师信息.xls"'); 
		header('Cache-Control: max-age=0');
		// 针对 IE 9
		header('Cache-Control: max-age=1');
		header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
		header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
		header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
		header ('Pragma: public'); // HTTP/1.0

		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter->save('php://output');
		exit();
	}

	/**
	 * @desc 接收excel文件导入教师信息
	 */
	public function upLoadTeacherAction(){
		if ($_POST) {

			$upload_dir     = WWW_ROOT . "uploads/teacher";
			$errUrl         = "admin/error/";
			$fileFieldName  = 'infoFile';
			$excelModel     = new ExcelModel();

			//确定存放文件的文件夹存在
			$excelModel->createUploadsDir($upload_dir, $errUrl);

			//文件上传可能出现的错误
			$excelModel->getErrors($fileFieldName);
			 
			//文件重命名
			$fileName = $excelModel->renameFile($upload_dir."/",$fileFieldName);

			//储存文件
			if (move_uploaded_file($_FILES[$fileFieldName]['tmp_name'],$fileName)){
			
				date_default_timezone_set('Asia/Shanghai');
				$inputFileName = $fileName;
				$objPHPExcel = PHPExcel_IOFactory::load($inputFileName) or
					header("Location: ".SITE_ROOT.$errUrl."msg/文件不存在");
				//从文件中读取数据
				$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
				$sheetData = array_slice($sheetData, 1);

				//将数据保存到数据库中
				foreach ($sheetData as $data) {
					$teacherInfo = array('uid'=>$data['A'],'name'=>$data['B']);
					$userInfo = array('uid'=>$data['A'], 'mid'=>2, 'password'=>$data['A']);

					$userModel = new LoginModel();
					$num = $userModel->insertUser($userInfo);
					if($num==0){
						//保存数据到teacher表中
						$teacherModel = new TeacherModel();
						$result = $teacherModel->insertTeacher($teacherInfo);
					}

				}
				header("Location: ".SITE_ROOT."admin/success/msg/".$this->parameters['okMsg'][5]);
			}else{
				header("Location: ".SITE_ROOT.$errUrl."msg/".$this->parameters['errMsg'][11]);
				exit();
			}


		}

	}

	/**
	 * @desc 搜索指定的教师
	 */
	public function searchTeacherAction(){
		//获取搜索关键字
		$searchKey = trim($this->get('searchKey'));

		$allTeacher   = array();
		$display      = false;
		$teacherModel = new TeacherModel();
		if ($teacher = $teacherModel->getOneTeacher($searchKey)) {
			$display = true;
			$allTeacher[] = $teacher;
		}else{
			$allTeacher = $teacherModel->getTeachersByName($searchKey);
			if (!empty($allTeacher)) {
				$display = true;
			}
		}
		if ($display==true) {
			//获取teacher表的所有字段名
			$fieldName = $teacherModel->field;

			$sex = $this->parameters['sex'];

			$this->assign(array('allTeacher' => $allTeacher,
								'fieldName'  => $fieldName,
								'sex'        => $sex,));
		}
	}

	/*********************************教师操作结束************************/
	/*********************************班级操作开始************************/
	/**
	 *@desc显示所有教师信息
	 *@param string $page 跳转页码
	 */
	public function showClassesAction($page=1){
		$classModel = new ClassModel();

		//获取所有班级信息
		$allClass   = $classModel->getAllClassInfo();

		//获取class表的所有字段名
		$fieldName    = $classModel->field;

		//分页框
		$currentPage  = $page?$page:1;
		$numberOfPage = $this->numberOfPage;
		$totalPages   = ceil(count($allClass)/$numberOfPage);
		if ($allClass && $currentPage>$totalPages) {
			header("Location: ".SITE_ROOT."admin/error/msg/您访问了不存在页面");
				exit();
		}
		$url 		  = SITE_ROOT."admin/show-classes/page/";
		$pagination   = $this->commonModel->paginator($currentPage, $totalPages, $url);
		//得到当页要显示的班级信息
		$allClass = array_slice($allClass, ($currentPage-1)*$numberOfPage, $numberOfPage); 
		
		$this->assign(array('allClass'  => $allClass,
							'fieldName' => $fieldName,
							'pagination' => $pagination));
	}

	/**
	 * @desc 添加班级
	 */
	public function addClassAction(){

 		//从表单获取数据并保存数据
		if ($class_id = trim($this->post('cid'))) {
			$classname = trim($this->post('classname'));
			$persons   = trim($this->post('persons'));

			$form      = array('class_id'=>$class_id,'classname'=>$classname);
			$classInfo = array_merge($form, array('persons'=>$persons));
	
			//验证必填项信息
			if (!$this->commonModel->isNull($form)) {
				$this->ajax(false, $this->parameters['errMsg'][1],1);
			}

			//将信息插入class表中
			$classModel   = new ClassModel('class_id');
			$result = $classModel->insertClass(array('class_id'=>$class_id,'classname'=>$classname,'persons'=>$persons));
			($result==14) && $this->ajax(false,$this->parameters['errMsg'][14],14);
			($result==0) && $this->ajax(true,$this->parameters['okMsg'][8]);
		}
	}

	/**
	 * @desc 修改班级信息
	 */
	public function updateClassAction(){

		$id = $this->get('id');
		$classModel = new ClassModel();
		if ($id=trim($id)) {
			$class = $classModel->getOneClass($id);
			$this->assign(array('class' => $class));
		}

 		//从表单获取数据并保存数据
		if ($class_id = trim($this->post('class_id'))) {
			$classname = trim($this->post('classname'));
			$persons   = intval($this->post('persons'));

			$form     = array('class_id'=>$class_id,'classname'=>$classname);
			$classInfo = array_merge($form, array('persons'=>$persons));

			//验证必填项信息
			if (!$this->commonModel->isNull($form)) {
				$this->ajax(false, $this->parameters['errMsg'][1], 1);
			}

			$classModel = new ClassModel('class_id');
			$result = $classModel->updateClass($classInfo);
			($result==17) && $this->ajax(false,$this->parameters['errMsg'][17],1);
			if($result==0){
				$this->ajax(true,$this->parameters['okMsg'][10]);
			}
		}
	}

	/**
	 * @desc 删除指定的班级
	 */
	public function deleteClassAction(){

		$class_id = $this->get('id');
		(!$class_id) && 
			header("Location: ".SITE_ROOT."admin/error/msg/".$this->parameters['errMsg'][15]);

		$classModel = new ClassModel();
		$class      = $classModel->getOneClass($class_id);
		if(intval($class['persons'])>0){
			header("Location: ".SITE_ROOT."admin/error/msg/".$this->parameters['errMsg'][16]);
			exit();
		}
		//从class表中删除数据
		$result = $classModel->deleteClass($class_id);

		if ($result==0) {
			$msg = $this->parameters['okMsg'][9];
			header("Location: ".SITE_ROOT."admin/success/msg/".$msg);
			exit();
		}
		($result==15) && header("Location: ".SITE_ROOT."admin/error/msg/".$this->parameters['errMsg'][15]);
		exit();
	}

	/**
	 *@desc显示指定班级所有学生信息
	 *@param string $page 跳转页码
	 */
	public function detailClassAction(){

		$class_id = $this->get('id');
		$classModel = new ClassModel();
		$class    = $classModel->getOneClass($class_id);
		//获取所有学生信息
		$allStudent   = $this->studentModel->getStudentsByCid($class_id);

		//获取student表的所有字段名
		$fieldName    = $this->studentModel->field;

		$sex          = $this->parameters['sex'];
		
		$this->assign(array('allStudent' => $allStudent,
							'fieldName'  => $fieldName,
							'sex'        => $sex,
							'class'   => $class));
	}

	/**
	 * @desc 导出班级信息以excel格式保存
	 */
	public function downLoadClassAction(){

		/*获取所有班级信息*/
		$classModel = new ClassModel();
		$allClass   = $classModel->getAllClassInfo();
		$fieldName    = $classModel->field;

		date_default_timezone_set('Asia/Shanghai');

		if (PHP_SAPI == 'cli')
			die('请使用浏览器进行操作！');

		// 生成 PHPExcel 对象
		$objPHPExcel = new PHPExcel();

		//设置文件属性
		$objPHPExcel->getProperties()->setCreator("傅道集")
									 ->setTitle("班级信息表")//文档名称
									 ->setSubject("班级信息表")
									 ->setDescription("理学院班级基本信息")
									 ->setKeywords("班级 信息");
		//添加列名称
		$objPHPExcel->setActiveSheetIndex(0)
		            ->setCellValue('A1', $fieldName['class_id']['comment'])
		            ->setCellValue('B1', $fieldName['classname']['comment'])
		            ->setCellValue('C1', $fieldName['persons']['comment']);

		//添加具体信息
		$i = 2;
		foreach ($allClass as $class) {
			$objPHPExcel->setActiveSheetIndex(0) 
		            ->setCellValue('A'.$i, $class['class_id'])
		            ->setCellValue('B'.$i, $class['classname'])
		            ->setCellValue('C'.$i, $class['persons']);
		    $i++;
		}

		//更改sheet名
		$objPHPExcel->getActiveSheet()->setTitle('班级信息表');  

		//设置打开文件时显示的sheet
		$objPHPExcel->setActiveSheetIndex(0);  


		//设置文件类型
		header('Content-Type: application/vnd.ms-excel');  
		//设置默认的文件名
		header('Content-Disposition: attachment;filename="班级信息.xls"'); 
		header('Cache-Control: max-age=0');
		// 针对 IE 9
		header('Cache-Control: max-age=1');
		header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
		header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
		header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
		header ('Pragma: public'); // HTTP/1.0

		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter->save('php://output');
		exit();
	}


	/**
	 * @desc 搜索指定的班级
	 */
	public function searchClassAction(){
		//获取搜索关键字
		$searchKey = trim($this->get('searchKey'));

		$allClass = array();
		$display  = false;
		$classModel = new ClassModel();
		if ($class = $classModel->getOneClass($searchKey)) {
			$display = true;
			$allClass[] = $class;
		}else{
			$classModel->classname;
			$allClass = $classModel->where("classname like '%$searchKey%'")->fList();
			if (!empty($allClass)) {
				$display = true;
			}
		}
		if ($display==true) {
			//获取class表的所有字段名
			$fieldName = $classModel->field;

			$this->assign(array('allClass' => $allClass,
								'fieldName'  => $fieldName));
		}
	}


	/*********************************班级操作结束************************/
	/*********************************课程操作开始************************/
	/**
	 *@desc显示所有课程信息
	 *@param string $page 跳转页码
	 */
	public function showCoursesAction($page=1){
		$courseModel  = new CourseModel();
		$teacherModel = new TeacherModel();
		$allTeacher   = $teacherModel->getAllTeacherInfo(); 
		

		//获取所有课程信息
		$allCourse   = $courseModel->getAllCourseInfo();

		//获取course表的所有字段名
		$fieldName    = $courseModel->field;

		//分页框
		$currentPage  = $page?$page:1;
		$numberOfPage = $this->numberOfPage;
		$totalPages   = ceil(count($allCourse)/$numberOfPage);
		if ($allCourse && $currentPage>$totalPages) {
			header("Location: ".SITE_ROOT."admin/error/msg/您访问了不存在页面");
				exit();
		}
		$url 		  = SITE_ROOT."admin/show-courses/page/";
		$pagination   = $this->commonModel->paginator($currentPage, $totalPages, $url);
		//得到当页要显示的课程信息
		$allCourse = array_slice($allCourse, ($currentPage-1)*$numberOfPage, $numberOfPage); 
		$term      = $this->parameters['term'];
		$active    = $this->parameters['active']; 
		//专业获取专业信息
		$majorModel = new MajorModel();
		$allMajor   = $majorModel->getAllMajorInfo();

		$this->assign(array('allCourse' => $allCourse,
							'allTeacher'=>$allTeacher,
							'allMajor' => $allMajor,
							'active' => $active, 	
							'term' => $term,	
							'fieldName' => $fieldName,
							'pagination' => $pagination));
	}

	/**
	 *@desc显示所有课程信息
	 *@param string $page 跳转页码
	 */
	public function showActiveCoursesAction($page=1){
		$courseModel  = new CourseModel();
		$teacherModel = new TeacherModel();
		$allTeacher   = $teacherModel->getAllTeacherInfo(); 
		

		//获取所有课程信息
		$allCourse   = $courseModel->getAllCourseInfo($active=true);

		//获取course表的所有字段名
		$fieldName    = $courseModel->field;

		//分页框
		$currentPage  = $page?$page:1;
		$numberOfPage = $this->numberOfPage;
		$totalPages   = ceil(count($allCourse)/$numberOfPage);
		if ($allCourse && $currentPage>$totalPages) {
			header("Location: ".SITE_ROOT."admin/error/msg/您访问了不存在页面");
				exit();
		}
		$url 		  = SITE_ROOT."admin/show-active-courses/page/";
		$pagination   = $this->commonModel->paginator($currentPage, $totalPages, $url);
		//得到当页要显示的课程信息
		$allCourse = array_slice($allCourse, ($currentPage-1)*$numberOfPage, $numberOfPage); 
		$term      = $this->parameters['term'];
		$active    = $this->parameters['active']; 
		//专业获取专业信息
		$majorModel = new MajorModel();
		$allMajor   = $majorModel->getAllMajorInfo();

		$this->assign(array('allCourse' => $allCourse,
							'allTeacher'=>$allTeacher,
							'allMajor' => $allMajor,
							'active' => $active, 	
							'term' => $term,	
							'fieldName' => $fieldName,
							'pagination' => $pagination));
	}

	/**
	 * @desc 开设课程
	 */
	public function addCourseAction(){

		$term   = $this->parameters['term'];
		$active = $this->parameters['active'];
		$teacherModel = new TeacherModel();
		$allTeacher = $teacherModel->getAllTeacherInfo();
		//专业获取专业信息
		$majorModel = new MajorModel();
		$allMajor   = $majorModel->getAllMajorInfo();

		$this->assign(array('term'  => $term,
							'active'=> $active,
							'allMajor'=>$allMajor,
							'allTeacher' => $allTeacher));

 		//从表单获取数据并保存数据
		if ($course_id = trim($this->post('courseId'))) {
			$coursename  = trim($this->post('courseName'));
			$description = trim($this->post('description'));
			$term        = trim($this->post('term'));
			$credit      = trim($this->post('credit'));
			$hours       = trim($this->post('hours'));
			$plimit      = trim($this->post('plimit'));
			$active      = trim($this->post('active'));
			$tid         = trim($this->post('tid'));
			$major_id    = trim($this->post('major_id'));

			$form = array('course_id'=>$course_id,'coursename'=>$coursename,
						  'term'=>$term,'credit'=>$credit,'hours'=>$hours,
						  'plimit'=>$plimit,'active'=>$active);
			$courseInfo = array_merge($form, array('description'=>$description,
												   'tid'=>$tid,'major_id'=>$major_id));
	
			//验证必填项信息
			if (!$this->commonModel->isNull($form)) {
				$this->ajax(false, $this->parameters['errMsg'][1],1);
			}

			//将信息插入course表中
			$courseModel   = new CourseModel('course_id');
			$result = $courseModel->insertCourse($courseInfo);
			($result==19) && $this->ajax(false,$this->parameters['errMsg'][19],19);
			($result==0) && $this->ajax(true,$this->parameters['okMsg'][11]);
		}
	}

	/**
	 * @desc 删除指定的课程
	 */
	public function deleteCourseAction(){

		$course_id = $this->get('id');
		(!$course_id) && 
			header("Location: ".SITE_ROOT."admin/error/msg/".$this->parameters['errMsg'][20]);

		$courseModel = new CourseModel();
		$course      = $courseModel->getOneCourse($course_id);
		if(intval($course['active'])==1){
			header("Location: ".SITE_ROOT."admin/error/msg/".$this->parameters['errMsg'][21]);
			exit();
		}

		//从course表中删除数据
		$result = $courseModel->deleteCourse($course_id);
		/*header("Location: ".SITE_ROOT."admin/success/msg/".$result);
		exit();*/
		if ($result==0) {
			$msg = $this->parameters['okMsg'][12];
			header("Location: ".SITE_ROOT."admin/success/msg/".$msg);
			exit();
		}
		($result==20) && header("Location: ".SITE_ROOT."admin/error/msg/".$this->parameters['errMsg'][20]);
		exit();
	}

	/**
	 *@desc修改课程信息
	 */
	public function updateCourseAction(){

		$course_id = $this->get('id');
		if ($course_id) {
			$fieldName = $courseModel->field;
			$term      = $this->parameters['term'];
			$active    = $this->parameters['active'];
			$courseModel  = new CourseModel();
			$teacherModel = new TeacherModel();
			$allTeacher   = $teacherModel->getAllTeacherInfo();
			$course = $courseModel->getOneCourse($course_id);
			//专业获取专业信息
			$majorModel = new MajorModel();
			$allMajor   = $majorModel->getAllMajorInfo();
			$this->assign(array('course'=>$course,
						  'allTeacher'=>$allTeacher,
						  'allMajor'=>$allMajor,
						  'fileName'=>$fieldName,
						  'term'=>$term,
						  'active'=>$active));
		}

		//从表单获取数据并保存数据
		if ($course_id = trim($this->post('courseId'))) {
			$coursename  = trim($this->post('courseName'));
			$description = trim($this->post('description'));
			$term        = trim($this->post('term'));
			$credit      = trim($this->post('credit'));
			$hours       = trim($this->post('hours'));
			$plimit      = trim($this->post('plimit'));
			$active      = trim($this->post('active'));
			$tid         = trim($this->post('tid'));
			$major_id    = trim($this->post('major_id'));

			$form = array('course_id'=>$course_id,'coursename'=>$coursename,
						  'term'=>$term,'credit'=>$credit,'hours'=>$hours,
						  'plimit'=>$plimit,'active'=>$active);
			$courseInfo = array_merge($form, array('course_description'=>$description,
												   'tid'=>$tid,'major_id'=>$major_id));
	
			//验证必填项信息
			if (!$this->commonModel->isNull($form)) {
				$this->ajax(false, $this->parameters['errMsg'][1],1);
			}

			//将信息插入course表中
			$courseModel   = new CourseModel('course_id');
			$result = $courseModel->updateCourse($courseInfo);
			($result==22) && $this->ajax(false,$this->parameters['errMsg'][22],22);
			($result==0) && $this->ajax(true,$this->parameters['okMsg'][13]);
		}
		 
	}

	/**
	 * @desc 搜索指定的课程
	 */
	public function searchCourseAction(){
		//获取搜索关键字
		$searchKey = trim($this->get('searchKey'));
		$term      = $this->parameters['term'];
		$active    = $this->parameters['active'];
		$teacherModel = new TeacherModel();
		$allTeacher   = $teacherModel->getAllTeacherInfo(); 

		$allCourse = array();
		$display   = false;
		$courseModel = new CourseModel('coursename');
		$allCourse = $courseModel->where("`coursename` like '%$searchKey%'")->fList();

		!empty($allCourse) && $display = true;
		if ($display==true) {
			//获取class表的所有字段名
			$fieldName = $courseModel->field;
			$this->assign(array('allCourse' => $allCourse,
								'fieldName' => $fieldName,
								'term' => $term,
								'active' => $active,
								'allTeacher' => $allTeacher));
		}
	}

	/**
	 * @desc 导出课程信息以excel格式保存
	 */
	public function downLoadCourseAction($active){

		/*获取所有课程信息*/
		$courseModel = new CourseModel();
		if(trim($active)=='true') $allCourse = $courseModel->getAllCourseInfo($active=true);
		else $allCourse = $courseModel->getAllCourseInfo();
		
		$fieldName   = $courseModel->field;
		$term        = $this->parameters['term'];
		$teacherModel = new TeacherModel();
		$allTeacher   = $teacherModel->getAllTeacherInfo(); 

		date_default_timezone_set('Asia/Shanghai');

		if (PHP_SAPI == 'cli')
			die('请使用浏览器进行操作！');

		// 生成 PHPExcel 对象
		$objPHPExcel = new PHPExcel();

		//设置文件属性
		$objPHPExcel->getProperties()->setCreator("傅道集")
									 ->setTitle("课程信息表")//文档名称
									 ->setSubject("课程信息表")
									 ->setDescription("理学院课程基本信息")
									 ->setKeywords("课程 信息");
		//添加列名称
		$objPHPExcel->setActiveSheetIndex(0)
		            ->setCellValue('A1', $fieldName['course_id']['comment'])
		            ->setCellValue('B1', $fieldName['coursename']['comment'])
		            ->setCellValue('C1', $fieldName['term']['comment'])
		            ->setCellValue('D1', $fieldName['credit']['comment'])
		            ->setCellValue('E1', $fieldName['hours']['comment'])
		            ->setCellValue('F1', $fieldName['plimit']['comment'])
		            ->setCellValue('G1', $fieldName['tid']['comment']);

		//添加具体信息
		$i = 2;
		foreach ($allCourse as $course) {
			$objPHPExcel->setActiveSheetIndex(0) 
		            ->setCellValue('A'.$i, $course['course_id'])
		            ->setCellValue('B'.$i, $course['coursename'])
		            ->setCellValue('C'.$i, $term[$course['term']])
		            ->setCellValue('D'.$i, $course['credit'])
		            ->setCellValue('E'.$i, $course['hours'])
		            ->setCellValue('F'.$i, $course['plimit'])
		            ->setCellValue('G'.$i, $allTeacher[$course['tid']]['name']);
		    $i++;
		}

		//更改sheet名
		$objPHPExcel->getActiveSheet()->setTitle('课程信息表');  

		//设置打开文件时显示的sheet
		$objPHPExcel->setActiveSheetIndex(0);  


		//设置文件类型
		header('Content-Type: application/vnd.ms-excel');  
		//设置默认的文件名
		header('Content-Disposition: attachment;filename="课程信息.xls"'); 
		header('Cache-Control: max-age=0');
		// 针对 IE 9
		header('Cache-Control: max-age=1');
		header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
		header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
		header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
		header ('Pragma: public'); // HTTP/1.0

		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter->save('php://output');
		exit();
	}
	/*********************************课程操作结束************************/
	/*********************************成绩操作开始************************/
	/**
	 *@desc显示指定课程的所有学生的成绩
	 *@param string $course_id 课程id
	 */
	public function showCourseGradesAction(){

		$course_id = $this->get('id');
		$courseModel = new CourseModel();
		$course   = $courseModel->getOneCourse($course_id);
		//获取某门课程的所有学生成绩
		$gradeModel = new GradeModel("course_id");
		$allGrades = $gradeModel->getAllGradeInfo($course_id);
		//获取选择某课程的所有学生信息
		$allStudent = $this->studentModel->getAllStudentInfo();

		//获取student表的所有字段名
		//$fieldName  = $this->gradeModel->field;
		$term = $this->parameters['term'];
		
		$this->assign(array('allGrades' => $allGrades,
							'term'  => $term,
							'allStudent' => $allStudent,
							'course'   => $course));
	}

	/**
	 * @desc 导出成绩单以excel格式保存
	 */
	public function downLoadGradeAction(){
		//获取指定课程的所有信息
		$course_id = $this->get('id');
		$courseModel = new CourseModel();
		$course   = $courseModel->getOneCourse($course_id);

		$term = $this->parameters['term'];
		$sheetTitle = $course['coursename']."成绩单"."-".$term[$course['term']];
		//获取指定课程的所有学生成绩
		$gradeModel = new GradeModel("course_id");
		$allGrades = $gradeModel->getAllGradeInfo($course_id);

		//获取所有学生信息以键值对的形式保存
		$allStudent = $this->studentModel->getAllStudentInfo();

		date_default_timezone_set('Asia/Shanghai');

		if (PHP_SAPI == 'cli')
			die('请使用浏览器进行操作！');

		// 生成 PHPExcel 对象
		$objPHPExcel = new PHPExcel();

		//设置文件属性
		$objPHPExcel->getProperties()->setCreator("傅道集")
									 ->setTitle($sheetTitle)//文档名称
									 ->setSubject("成绩信息表")
									 ->setDescription("理学院".$sheetTitle."信息")
									 ->setKeywords("成绩单 信息");
		//添加列名称
		$objPHPExcel->setActiveSheetIndex(0)
		            ->setCellValue('A1', "学号")
		            ->setCellValue('B1', "姓名")
		            ->setCellValue('C1', "成绩")
		            ->setCellValue('D1', "名次");

		//添加具体信息
		$i = 2;
		foreach ($allGrades as $grade) {
			$objPHPExcel->setActiveSheetIndex(0) 
		            ->setCellValue('A'.$i, $grade['student_id'])
		            ->setCellValue('B'.$i, $allStudent[$grade['student_id']]['name'])
		            ->setCellValue('C'.$i, $grade['score'])
		            ->setCellValue('D'.$i, $i-1);
		    $i++;
		}

		//更改sheet名
		$objPHPExcel->getActiveSheet()->setTitle($sheetTitle);  

		//设置打开文件时显示的sheet
		$objPHPExcel->setActiveSheetIndex(0);  


		//设置文件类型
		header('Content-Type: application/vnd.ms-excel');  
		//设置默认的文件名
		header("Content-Disposition: attachment;filename='".$sheetTitle.".xls'"); 
		header('Cache-Control: max-age=0');
		// 针对 IE 9
		header('Cache-Control: max-age=1');
		header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
		header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
		header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
		header ('Pragma: public'); // HTTP/1.0

		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter->save('php://output');
		exit();
	}

	/*********************************成绩操作结束************************/
	
	/**
	 * @desc 操作失败的提示信息
	 *@param string $msg 提示信息的内容
	 */
	public function resetUserPwdAction(){
		if ($uid = trim($this->post('uid'))) {
			$newPwd     = trim($this->post('newPwd'));
			$confirmPwd = trim($this->post('confirmPwd'));

			$info = array('uid'=>$uid, 'newPwd'=>$newPwd, 'confirmPwd'=>$confirmPwd);
			/*验证表单数据是否为空*/
			$commonModel = new CommonModel();
			if (!$commonModel->isNull($info)) {
				$this->ajax(false, $this->parameters['errMsg'][1]);
			}

			//返回密码修改结果，修改成功的返回0,返回其他数字都表示有错误
			$loginModel = new LoginModel();
			$result = $loginModel->resetPassword($info, $self=false);
			($result==3) && $this->ajax(false, $this->parameters['errMsg'][3], 3);
			($result==7) && $this->ajax(false, $this->parameters['errMsg'][7], 7);
			($result==0) && $this->ajax(true, $uid);
			$this->ajax(false, $this->parameters['errMsg'][18],18);
		}
	}

	/**
	 * @desc 操作成功的提示信息
	 *@param string $msg 提示信息内容
	 */
	public function successAction($msg=''){
		$this->assign(array('msg' => $msg));
	}

	/**
	 * @desc 操作失败的提示信息
	 *@param string $msg 提示信息的内容
	 */
	public function errorAction($msg=''){
		$this->assign(array('msg' => $msg));
	}

	/**
	 * @desc 开发过程中的测试页面
	 */
	/*public function testAction(){
		date_default_timezone_set('Asia/Shanghai');
		$inputFileName = '/home/fudaoji/download/学生信息 .xls';
		$objPHPExcel = PHPExcel_IOFactory::load($inputFileName); //or
			//header("Location: ".SITE_ROOT."admin/error/msg/文件不存在");

		$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
		//header("Location: ".SITE_ROOT."admin/success/msg/成功");
		$this->assign(array('sheetData'=>$sheetData));
	}*/



	

}